package org.aeon.gamechatnest.service.impl;

import org.aeon.gamechatnest.common.response.RespStatus;
import org.aeon.gamechatnest.common.response.ResultBuild;
import org.aeon.gamechatnest.exception.ApplicationException;
import org.aeon.gamechatnest.mapper.BlacklistMapper;
import org.aeon.gamechatnest.mapper.FriendMapper;
import org.aeon.gamechatnest.mapper.FriendRequestMapper;
import org.aeon.gamechatnest.mapper.UserMapper;
import org.aeon.gamechatnest.pojo.Friend;
import org.aeon.gamechatnest.pojo.FriendRequest;
import org.aeon.gamechatnest.service.FriendRequestService;
import org.aeon.gamechatnest.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


/**
 * 好友请求服务类
 *
 * @author : Qik 2024/5/9 10:09
 */
@Service
public class FriendRequestServiceImpl implements FriendRequestService {

    @Autowired
    private FriendRequestMapper friendRequestMapper;

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BlacklistMapper blacklistMapper;

    @Override
    @Transactional(rollbackFor = ApplicationException.class)
    public boolean save(FriendRequest friendRequest) {
        // 获取登录用户id
        Long loginUserId = SecurityUtil.getUserId();

        // 验证目标用户非自身
        Long toUser = friendRequest.getToUser();
        if (toUser.equals(loginUserId)) {
            ResultBuild.result().state(RespStatus.PARAM_ERROR).message("不能向自己发送请求");
            return false;
        }
        // 验证目标用户是否存在
        if (userMapper.selectById(toUser) == null) {
            ResultBuild.result().state(RespStatus.PARAM_ERROR).message("目标用户不存在");
            return false;
        }
        // 验证黑名单（被对方拉黑）
        if (blacklistMapper.getByFromAndTo(toUser, loginUserId) != null) {
            ResultBuild.result().state(RespStatus.NO_PERMISSION).message("无法添加该用户");
            return false;
        }
        // 验证黑名单（拉黑对方）
        if (blacklistMapper.getByFromAndTo(loginUserId, toUser) != null) {
            ResultBuild.result().state(RespStatus.NO_PERMISSION).message("该用户已被你拉黑，无法添加");
            return false;
        }

        // 请求是否已存在
        FriendRequest existFriendRequest = friendRequestMapper.getByBothSides(loginUserId, toUser);
        if (existFriendRequest != null) {
            Integer verifyStatus = existFriendRequest.getVerifyStatus();
            switch (verifyStatus) {
                // 未通过
                case 0 -> {
                    if (existFriendRequest.getToUser().equals(loginUserId)) {
                        // 如果是对方也发了好友请求，直接添加好友
                        Friend friend = FriendServiceImpl.getFriend(existFriendRequest, existFriendRequest.getToUser());
                        if (friend == null) return false;
                        // 新增好友
                        int added = friendMapper.add(friend);
                        // 更新好友请求状态
                        int updated = friendRequestMapper.updateVerifyStatus(existFriendRequest.getRequestId(), 1);
                        if (added != 1 || updated != 1) {
                            throw new ApplicationException(RespStatus.FAIL, "系统错误，新增失败");
                        } else {
                            ResultBuild.result().message("已成功添加对方好友");
                            return true;
                        }
                    } else {
                        ResultBuild.result().state(RespStatus.DUPLICATE_KEY_ERROR).message("好友请求已发送，请等待结果");
                        return false;
                    }
                }
                // 已通过
                case 1 -> {
                    ResultBuild.result().state(RespStatus.DUPLICATE_KEY_ERROR).message("已添加为好友，请勿重复添加");
                    return false;
                }
                // 被拒绝，删除之前的请求重新发送
                case 2 -> {
                    int deleted = friendRequestMapper.deleteById(existFriendRequest.getRequestId());
                    if (deleted != 1) throw new ApplicationException(RespStatus.FAIL, "系统错误，请求失败");
                }
            }
        }

        // 发送用户
        friendRequest.setFromUser(loginUserId);
        // 新增时间
        friendRequest.setCreateTime(new Date());
        // 默认状态0：未通过
        friendRequest.setVerifyStatus(0);

        return friendRequestMapper.add(friendRequest) == 1;
    }

    @Override
    public FriendRequest find(Long id) {
        // 获取登录用户id
        Long loginUserId = SecurityUtil.getUserId();

        FriendRequest friendRequest = friendRequestMapper.getById(id);
        // 好友请求不存在
        if (friendRequest == null) {
            ResultBuild.result().state(RespStatus.NOT_FOUND).message("好友请求不存在");
            return null;
        }
        // 获取请求双方用户id
        Long fromUser = friendRequest.getFromUser();
        Long toUser = friendRequest.getToUser();
        // 校验该请求是否属于登录用户（用户不是发送者也不是接收者）
        if (!fromUser.equals(loginUserId) && !toUser.equals(loginUserId)) {
            ResultBuild.result().state(RespStatus.NO_PERMISSION).message("无权查看该请求");
            return null;
        }
        return friendRequest;
    }

    @Override
    public List<FriendRequest> findReceive() {
        return friendRequestMapper.getUnPassByToUser(SecurityUtil.getUserId());
    }
}
